package com.example.user_module.arouterservice;

import android.content.Context;

import androidx.room.Room;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.SPUtils;
import com.example.base_application_sdk.BaseApplication;
import com.example.common.entity.BaseEntity;
import com.example.common.prowviderservice.CheckLoginApi;
import com.example.user_module.login.RoomUserEntity;
import com.example.user_module.room.AppDatabase;

import java.util.List;

import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

@Route(path = "/user/checklogin")
public class CheckLoginApiImpl implements CheckLoginApi {
    private Observable<BaseEntity> observable;
    private AppDatabase database;
    @Override
    public boolean checkLogin() {
        return SPUtils.getInstance().getBoolean("isLogin",false);
    }

    @Override
    public Observable<BaseEntity> getUserInfo() {
        return observable;
    }

    @Override
    public void init(Context context) {
        database = Room.databaseBuilder(BaseApplication.getInstance(), AppDatabase.class, "login.db").build();
        Maybe<List<RoomUserEntity.InsertUserValuesEntity>> query = database.userDao().query();
        observable = query.flatMapObservable(new Function<List<RoomUserEntity.InsertUserValuesEntity>, ObservableSource<? extends BaseEntity>>() {
            @Override
            public ObservableSource<? extends BaseEntity> apply(List<RoomUserEntity.InsertUserValuesEntity> insertUserValuesEntities) throws Exception {
                RoomUserEntity roomUserEntity = new RoomUserEntity();
                roomUserEntity.data=new RoomUserEntity.InsertUserValueEntity();
                roomUserEntity.data.data = insertUserValuesEntities.get(insertUserValuesEntities.size()-1);
                Observable<RoomUserEntity> just = Observable.just(roomUserEntity);
                return just.map(new Function<RoomUserEntity, BaseEntity>() {
                    @Override
                    public BaseEntity apply(RoomUserEntity roomUserEntity) throws Exception {
                        return roomUserEntity;
                    }
                });
            }
        });
    }
}
